package com.api.syh56.shengyunhui.service.impl;

import cn.hutool.core.net.URLDecoder;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.syh56.shengyunhui.common.BaseUserInfo;
import com.api.syh56.shengyunhui.common.CommonResult;
import com.api.syh56.shengyunhui.common.UserInfoEnu;
import com.api.syh56.shengyunhui.entity.Address;
import com.api.syh56.shengyunhui.entity.BankCard;
import com.api.syh56.shengyunhui.entity.SystemMessage;
import com.api.syh56.shengyunhui.exception.BaseException;
import com.api.syh56.shengyunhui.mapper.BankCardMapper;
import com.api.syh56.shengyunhui.mapper.SystemMessageMapper;
import com.api.syh56.shengyunhui.service.BankCardService;
import com.api.syh56.shengyunhui.util.BankUtil;
import com.api.syh56.shengyunhui.util.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BankCardServiceImpl extends ServiceImpl<BankCardMapper, BankCard>  implements BankCardService {
    @Override
    public void addNewBankCard(BankCard bankCard) {
        Long uid = Long.valueOf(BaseUserInfo.get(UserInfoEnu.id.getCode()));

        QueryWrapper<BankCard> bankCardQueryWrapper = new QueryWrapper<>();
        bankCardQueryWrapper.lambda().eq(BankCard::getUid, uid);
        List<BankCard> list = list(bankCardQueryWrapper);
        for (BankCard bankcard : list) {
            if (bankcard.getBankAccount().equals(bankCard.getBankAccount())) {
                throw new BaseException("该银行卡号已存在");
            }
        }


        if (list.size() >= 3) {
            throw new BaseException("最多只能添加3张银行卡");
        }
        BankCard newBankcard = getBankNameAndLogo(bankCard);
        newBankcard.setUid(uid);
        save(newBankcard);
    }

    @Override
    public void removeBankCard(BankCard bankCard) {
        removeById(bankCard.getId());
    }

    @Override
    public Page<BankCard> selectPageByuid(Long uid, Integer pageSize, Integer pageNum) {
        Page<BankCard> page = new Page<>(pageNum,pageSize);
        QueryWrapper<BankCard> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(BankCard::getUid,uid);
        Page<BankCard> bankCardPage = page(page, wrapper);
        return bankCardPage;
    }


    public BankCard getBankNameAndLogo(BankCard bankCard)  {
        String cardNo = bankCard.getBankAccount();
        String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json";
        Map<String, String> map = new HashMap<String, String>();
        map.put("cardNo", cardNo);
        map.put("cardBinCheck", "true");
        String json_Str = HttpUtil.send(url, map, "utf-8");
        JSONObject Res = JSONObject.parseObject(json_Str);
        if (Res.get("validated").toString().equals("false")) {
            throw new BaseException("银行卡号错误");
        }
        String bankCode = Res.get("bank").toString();
        String nameOfBank = BankUtil.getNameOfBank(bankCode);

        String logourl =  "https://apimg.alipay.com/combo.png?d=cashier&t="+bankCode+"_s";


//        String path = this.getClass().getClassLoader().getResource("banks.json").getPath();//注意getResource("")里面是空字符串
//        System.out.println(path);

        // 指定JSON文件的路径
        String filePath = "static/banks.json";
        Gson gson = new Gson();
        JsonReader reader;
        try {
            reader = new JsonReader(new FileReader(filePath));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        Object obj = gson.fromJson(reader, Object.class);
        // 关闭 JsonReader
        try {
            reader.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 使用 Gson 的 toJson 方法，将 Java 对象转换为 JSON 字符串
        String jsonStr = gson.toJson(obj);

        // 将字符串转换为JSON数组
        List<Map> BankList = JSONObject.parseArray(jsonStr, Map.class);
        // 遍历JSON数组
        for (int i = 0; i < BankList.size(); i++) {
            Map bankMap = BankList.get(i);

            String abbrEn = (String) bankMap.get("abbr_en"); // 获取abbr_en值
            if (bankCode.equals(abbrEn)) {
                String icon = (String) bankMap.get("icon"); // 获取icon值
                System.out.println("Icon for " + abbrEn + ": " + icon);
                logourl = "https://syhcomm.oss-cn-beijing.aliyuncs.com/bankicons/"+icon;

                break; // 如果只需要找到第一个匹配项，找到后即可退出循环
            }
        }


        bankCard.setBankName(nameOfBank);
        bankCard.setLogo(logourl);
//        String logourl = "https://apimg.alipay.com/combo.png";
//        Map<String, String> logoMap = new HashMap<>();
//        logoMap.put("d", "cashier");
//        logoMap.put("t", bankCode);
//        String logoRes = HttpUtil.send(logourl, logoMap, "utf-8");

        return bankCard;
    }


}
